package com.example.demo.util;

import com.example.demo.handler.Action;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
import java.util.function.Supplier;

/**
 * Created by wanghuajie on 2018/9/5.
 */
public class ScheduledExecutor<T> {
    private static final Logger LOGGER = LoggerFactory.getLogger(ScheduledExecutor.class);

    private final ScheduledExecutorService executor;
    private final Action<T> act;

    public ScheduledExecutor(Action<T> d, String name) {
        this(d, name, 0, 500);
    }

    public ScheduledExecutor(Action<T> d, String name, long initDelay, long delay) {
        this.executor = Executors.newSingleThreadScheduledExecutor(r -> new Thread(r, "scheduled_exec_" + name));
        this.act = d;
        executor.scheduleWithFixedDelay(() -> {
            try {
                d.consume();
            } catch (Throwable t) {
                LOGGER.error("error found while action executing", t);
            } finally {
                d.clear();
            }
        }, initDelay, delay, TimeUnit.MILLISECONDS);
    }

    /**
     * 加入队列
     */
    public void submitAdd(Supplier<T> data) {
        if (data == null) return;
        executor.submit(() -> {
            T t = data.get();
            if (t != null) {
                act.add(t);
            }
        });
    }

}
